<template>
  <el-dialog
    :title="title"
    v-model="visible"
    width="1000px"
    @close="onClose"
    :close-on-click-modal="false"
  >
    <div class="main">
      <div class="type">优惠券名称：{{ couponName }}</div>
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="用户名称" prop="nickName">
          <el-input
            style="width: 200px"
            v-model.trim="queryParams.nickName"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="领取时间区间" prop="time">
          <el-date-picker
            style="width: 240px"
            v-model="queryParams.time"
            type="daterange"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            value-format="x"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="使用点位" prop="positionName">
          <el-input
            style="width: 200px"
            v-model.trim="queryParams.positionName"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="优惠券状态" prop="status">
          <el-select v-model="queryParams.status" fit-input-width clearable placeholder="请选择">
            <el-option label="全部状态" value=""></el-option>
            <el-option label="已使用" value="2"></el-option>
            <el-option label="未使用" value="1"></el-option>
            <el-option label="未领取" value="8" v-if="title === '导出详情'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" v-if="!props.validStartTime" @click="handleExtend">
            延长时间设置
          </el-button>
          <el-button type="primary" v-if="title === '已领取'" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="multipleTableRef" v-loading="loading" size="default" index :data="dataList">
        <el-table-column
          v-if="!props.validStartTime"
          type="selection"
          :selectable="selectable"
          width="55"
        />
        <el-table-column
          label="券码ID"
          min-width="125px"
          v-if="title === '导出详情'"
          align="center"
          prop="checkId"
        />
        <el-table-column label="用户名称" align="center" prop="nickName" />
        <el-table-column label="领取时间" width="160" align="center" prop="acquireTime" />
        <el-table-column label="用券时间" width="160" align="center" prop="useTime" />
        <el-table-column v-if="title === '已领取'" label="状态" align="center" prop="status">
          <template #default="{ row }">
            <span>{{ row.status === 2 ? '已使用' : row.status === 1 ? '未使用' : '未使用' }}</span>
          </template>
        </el-table-column>
        <el-table-column v-else label="状态" align="center" prop="useStatus">
          <template #default="{ row }">
            <span>{{
              row.useStatus === null ? '未领取' : row.useStatus === 2 ? '已使用' : '未使用'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="使用点位"
          show-overflow-tooltip
          align="center"
          prop="positionName"
        />
        <el-table-column v-if="title === '已领取'" label="操作" align="center" prop="name">
          <template #default="{ row }">
            <div>
              <el-link
                v-if="row.status === 1 || row.status === 4"
                style="margin-left: 6px"
                :underline="false"
                type="primary"
                @click="handleExpire(row.clientCouponId)"
                >失效</el-link
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column v-else label="操作" align="center" prop="name">
          <template #default="{ row }">
            <div>
              <el-link
                v-if="
                  row.useStatus !== 0 &&
                  row.useStatus !== 2 &&
                  row.receiveStatus !== 2 &&
                  row.useStatus !== 3
                "
                style="margin-left: 6px"
                :underline="false"
                type="primary"
                @click="handleExpire(row.checkId)"
                >失效</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-right: 10px">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 延长时间 -->
    <extendDialog
      ref="extendRef"
      :selectionList="selectionList"
      @refresh="handleClose"
      :title="title"
      type="1"
    />
  </el-dialog>
</template>

<script setup>
import {
  expireCouponApi,
  expireGetCouponApi,
  exportDetailApi,
  getClaimedCouponApi
} from '@/api/marketing/activity'
import extendDialog from './extendDialog.vue'
const queryRef = ref(null)
const props = defineProps({
  validStartTime: {
    type: String,
    default: ''
  }
})
const { proxy } = getCurrentInstance()

const emits = defineEmits(['close'])

const couponName = ref('')
const total = ref(0)
const dataList = ref([])
const visible = ref(false)
const title = ref('')

const queryParams = reactive({
  couponId: '',
  nickName: '',
  startTime: '',
  endTime: '',
  positionName: '',
  status: '',
  time: '',
  pageNum: 1,
  pageSize: 10
})
const loading = ref(true)

const multipleTableRef = ref(null)
const selectionList = ref([])
const extendRef = ref(null)

// 是否可选中
function selectable(row) {
  if (title.value === '导出详情') {
    if (row.useStatus === 1 || row.useStatus === 4) {
      return true
    }
  } else {
    if (row.status === 1 || row.status === 4) {
      return true
    }
  }
}

//延长时间  领取时效的券可以延长时间
function handleExtend() {
  if (!multipleTableRef.value.getSelectionRows().length) {
    return ElMessage({
      message: '请至少选择一个',
      type: 'error'
    })
  }
  selectionList.value = multipleTableRef.value
    .getSelectionRows()
    .map((i) => (title.value === '已领取' ? i.clientCouponId : i.checkId))
  extendRef.value.init()
}

function handleClose() {
  multipleTableRef.value.clearSelection()
  getList()
}
/**导出按钮 */
function handleExport() {
  const params = { ...queryParams }
  delete params.time
  delete params.pageNum
  delete params.pageSize
  proxy.download(
    'operation/marCoupon/exportAcquire',
    params,
    `已领取详情${new Date().getTime()}.xlsx`
  )
}
// 失效
function handleExpire(id) {
  ElMessageBox.confirm('该券将会被强制失效', '操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(() => {
      if (title.value === '已领取') {
        expireGetCouponApi({ clientCouponId: id }).then(() => {
          ElMessage({
            type: 'success',
            message: '操作成功'
          })
          handleQuery()
        })
        return
      }
      expireCouponApi({ checkId: id }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        handleQuery()
      })
    })
    .catch(() => {})
}

/** 查询用户列表 */
function getList() {
  loading.value = true
  const params = {
    ...queryParams,
    startTime: queryParams.time?.length ? queryParams.time[0] : '',
    endTime: queryParams.time?.length ? queryParams.time[1] : ''
  }
  delete params.time
  if (title.value === '已领取') {
    getClaimedCouponApi(params)
      .then((res) => {
        loading.value = false
        dataList.value = res?.data?.rows || []
        total.value = res?.data?.total || 0
      })
      .catch(() => {
        loading.value = false
        dataList.value = []
        total.value = 0
      })
  } else {
    exportDetailApi(params)
      .then((res) => {
        loading.value = false
        dataList.value = res?.data?.rows || []
        total.value = res?.data?.total || 0
      })
      .catch(() => {
        loading.value = false
        dataList.value = []
        total.value = 0
      })
  }
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  queryRef.value.resetFields()
  handleQuery()
}

function onClose() {
  queryRef.value.resetFields()
  queryParams.pageNum = 1
}

function init(row, name) {
  couponName.value = row.couponName
  visible.value = true
  queryParams.couponId = row.id
  title.value = name
  getList()
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
:deep(.pagination-container .el-pagination) {
  right: 20px;
}
.main {
  position: relative;
  transform: translate3d(0, -30px, 0);
}
.type {
  margin-bottom: 20px;
}
</style>
